package com.wenhai.redis.lettuce;

import io.lettuce.core.RedisClient;
import io.lettuce.core.RedisURI;
import io.lettuce.core.SetArgs;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.sync.RedisCommands;
import io.lettuce.core.support.ConnectionPoolSupport;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;

import java.time.Duration;
import java.time.temporal.ChronoUnit;

public class LettucePoolDemo {
    public static void main(String[] args) {
        RedisURI redisURI = RedisURI.builder()
                .withPassword("admin")
                .withHost("192.168.152.138")
                .withPort(6379)
                .withTimeout(Duration.of(10,ChronoUnit.SECONDS))
                .build();
        RedisClient redisClient = RedisClient.create(redisURI);
        GenericObjectPoolConfig<StatefulRedisConnection<String, String>> poolConfig = new GenericObjectPoolConfig<>();
        GenericObjectPool<StatefulRedisConnection<String, String>> pool
                = ConnectionPoolSupport.createGenericObjectPool(redisClient::connect, poolConfig);

        try(StatefulRedisConnection<String, String> connection = pool.borrowObject()) {
            RedisCommands<String, String> command = connection.sync();
            SetArgs args2 = SetArgs.Builder.nx().ex(10);
            command.set("name", "wenhai", args2);
            System.out.println(command.get("name"));

        } catch (Exception e) {
            e.printStackTrace();
        }
        pool.close();
        redisClient.shutdown();

    }
}
